package com.wn.servlet.demo01;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yellow Docter
 * @date 2022 -06-29
 * @desc
 *
 *  json 是 js的子集
 *  有2种格式:
 *  格式1:  key/value 的集合
 *
 *  {
 *      "name":"乔峰",
 *      "age":40,
 *      "phone":"1856623"
 *  }
 *
 *  格式2:
 *  值的有序列表:
 *  ["深圳","广州","武汉"]
 *
 *
 *  java中的json框架
 *  01   fastJson            阿里巴巴开源
 *  02   Gson                google开源
 *  03   Jackson             springmvc 默认集成的框架 (Jackson社区开源)
 *
 *  使用:
 *  01 添加jar
 *
 *  02 创建ObjectMapper对象
 *
 *    writeValueAsString(user);把java对象转成 json字符串
 *
 *    objectMapper.readValue(msg, User.class);  把json字符串 转化成java对象
 *
 *   FastJson
 *   将java对象 转为字符串
 *      String str= JSON.toJSONString(user);
 *   将json字符串转为java对象
 *       User user= JSON.parseObject(jsonStr, User.class);
 *
 *   Gson 的使用
 *      创建对象
 *      Gson gson = new Gson();
 *      把对象转成字符串
 *      String pJson = gson.toJson(user);
 *
 *      字符串转成java对象
 *      User user = gson.fromJson(gStr, User.class)
 */
public class UserApp {

    public static void main(String[] args) throws JsonProcessingException {

        // 把java 对象转成json 字符串
//        test01();

        // 把java集合转成json 字符串
        test02();

//        test03();

    }

    private static void test03() throws JsonProcessingException {
        String msg = "{\"name\":\"乔峰\",\"age\":40,\"phone\":\"1856623\"}";

        // 创建对象
        ObjectMapper objectMapper = new ObjectMapper();

        //把字符串转成 java对象
        User user = objectMapper.readValue(msg, User.class);
        System.out.println("user = " + user);
    }

    /**
     * 把java集合转成json 字符串
     * @throws JsonProcessingException
     */
    private static void test02() throws JsonProcessingException {
        List<User> users =new ArrayList<>();

        User user = new User();
        user.setName("乔峰");
        user.setAge(40);
        user.setPhone("1856623");

        User user2 = new User();
        user2.setName("王语嫣");
        user2.setAge(20);
        user2.setPhone("1856624");

        users.add(user);
        users.add(user2);

        ObjectMapper objectMapper = new ObjectMapper();

        String s = objectMapper.writeValueAsString(users);
        System.out.println("s = " + s);
    }

    /**
     * 把java对象转成json 字符串
     * @throws JsonProcessingException
     */
    private static void test01() throws JsonProcessingException {
        User user = new User();
        user.setName("乔峰");
        user.setAge(40);
        user.setPhone("1856623");

        // 创建 对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 把java对象转成json字符串
        String s = objectMapper.writeValueAsString(user);
        System.out.println("s = " + s);
    }
}
